import axios from 'axios'
// import utils from './utils'
import _ from "lodash"
import * as qs from 'qs'

const serverPath = process.env.VUE_APP_SERVER_PATH

const transformRequest = (data, headers) => {
    // if (!utils.isObject(data)) {
    if (!_.isObject(data)) {
        return data
    }
    for (var pkey in data) {
        if (data[pkey] === null || typeof (data[pkey]) === 'undefined') {
            delete data[pkey]
        }
    }
    const contentType = headers['Content-Type'];
    if (!contentType || contentType.includes('x-www-form-urlencoded')) {
        //data = utils.params(data);
        data = qs.stringify(data)
    }
    return data
}

axios.defaults.transformRequest.unshift(transformRequest)

const basePath = () => {
    let basePath = serverPath ? serverPath : location.protocol + '//' + location.host;
    if (basePath.charAt(basePath.length - 1) === '/') {
        basePath = basePath.substring(0, basePath.length - 1)
    }
    return basePath
}

const checkUrl = (url) => {
    if (url) {
        if (url.indexOf('http') !== 0) {
            url = basePath() + ( url.charAt(0) === '/' ? '' : '/') + url
        }
    } else {
        url = basePath()
    }
    return url
}

const instance = axios.create({
    baseURL: basePath()
})

instance.basePath = () => {
    return basePath()
}

instance.url = (url) => {
    return checkUrl(url)
}

instance.redirect = (url) => {
    window.location.href = instance.url(url)
}

instance.open = (url) => {
    window.open(instance.url(url))
}

instance.download = (url, options) => {
    if (!url) {
        return
    }
    if (url.indexOf('http') !== 0) {
        url = checkUrl(url)
    }
    if (_.isEmpty(options)) {
        options = {}
    }
    if (!_.isEmpty(options)) {
        // let data = utils.params(options)
        const data = qs.stringify(data)
        url += '?' + data
    }
    window.open(url)
}

instance.interceptors.request.use(config => {
    // 可以在这里加入ajax请求前处理的业务，如加入access_token
    if (config.url.indexOf('http') !== 0) {
        config.url = checkUrl(config.url)
    }
    return config
})

instance.interceptors.response.use(response => {
    return response.data
}, error => {
    if ('ERR_NETWORK' === error.code) {
        return Promise.reject({
            code: error.code,
            message: '网络异常, 请联系信息管理员',
            result: null
        })
    }
    let response = error.response.data || error.response
    if ('invalid_grant' === response.error) {
        response = {
            code: error.response.status,
            message: response.error_description,
            result: null
        }
    } else if (response.error) {
        response = {
            code: error.response.status,
            message: response.error_description || response.error,
            result: null
        }
    }
    return Promise.reject(response)
})

export default instance
